<?php

namespace Modules\Captcha\Services;

use App\Exceptions\BusinessException;
use App\Helpers\CodeResponse;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

// use App\Services\GetBytes;

class CaptchaService
{
    /**
     * 说明：生成图形验证码
     *
     * @return
     * @param   type
     * @author  daixinguo (daixinguo57@163.com)
     */
    public static function makeCaptcha($uuid, $data)
    {
        $path = module_path('Captcha');
        // 随机取一张图片 生成随机角度的临时图片 并将 用户账号、uuid、随机旋转角度保存到缓存中
        $image_path = $path . "/Resources/assets/captcha_images";
        $images = scandir($image_path);
        foreach ($images as $key => $value) {
            if ($value == '.' || $value == '..') {
                unset($images[$key]);
            }
        }
        $images = array_values($images);
        $random_img = $images[rand(0, count($images) - 1)];
        // 随机逆时针旋转角度
        $angle = rand(2000, 34000) / 100;
        $img = imagecreatefrompng($image_path . "/" . $random_img);
        // 设置旋转后图片填充区域的透明度
        $transparency = imagecolorallocatealpha($img, 255, 255, 255, 100);
        $img = imagerotate($img, $angle, $transparency, 1);
        $storage_path = Storage::disk("system")->path("captcha/");
        if (!is_dir($storage_path)) {
            Storage::disk("system")->makeDirectory("captcha");
        }
        $new_img = imagepng($img, $storage_path  . $uuid . ".png", 9, PNG_ALL_FILTERS);
        if (!$new_img) {
            throw new BusinessException(CodeResponse::SERVER, "图片验证码生成失败！");
        }
        // 将图片 uuid和图片的旋转角度存入缓存
        $key = md5($uuid . $data['username']);
        Cache::put($key, $angle, $seconds = 60);
        return [
            "image" => Storage::disk("system")->url("captcha/" . $uuid . ".png")
        ];
    }

    /**
     * 说明：验证图形验证码
     *
     * @return
     * @param   type
     * @author  daixinguo (daixinguo57@163.com)
     */
    public static function verifyCaptcha($uuid, $data)
    {
        // 删除图片
        Storage::disk("system")->delete("captcha/" . $uuid . ".png");
        $key = md5($uuid . $data['username']);
        $angle = Cache::get($key);
        Cache::forget($key);
        if (is_null($angle)) {
            throw new BusinessException(CodeResponse::VERIFICATION_CODE_FAIL, "图片验证码已失效，请重试！");
        }
        $fault_tolerant = config("captcha.fault_tolerant");
        if ($data['value'] > $angle - $fault_tolerant && $data['value'] < $angle + $fault_tolerant) {
            $captcha_token = md5((string) Str::uuid() . $data['username']);
            Cache::put($captcha_token, "pass", $seconds = 30);
            return [
                "captcha_token" => $captcha_token
            ];
        } else {
            throw new BusinessException(CodeResponse::VERIFICATION_CODE_FAIL, "验证失败，请重试！");
        }
    }
}
